package middlewares

import (
	"github.com/gin-gonic/gin"
	"mojieshi/define"
	"mojieshi/models"
	"net/http"
	"strconv"
)

// 验证请求头
func AuthTokenAdmin() gin.HandlerFunc {
	return func(c *gin.Context) {
		//从请求头获取数据
		token := c.GetHeader("token")
		userId, err := strconv.Atoi(c.GetHeader("userId")) //将字符串转为int
		//调用解析token方法
		UserClaim, err := define.AnalyseToken(token)
		if err != nil {
			c.Abort() //终止函数
			c.JSON(http.StatusOK, gin.H{
				"success": false,
				"code":    33000,
				"msg":     "Token错误",
			})
			return
		}
		if UserClaim.UserId != userId {
			c.Abort()
			c.JSON(http.StatusOK, gin.H{
				"success": false,
				"code":    33000,
				"msg":     "Token错误",
			})
			return
		}
		//数据库获取
		var user models.MAdminUser
		//根据主键查询
		err = models.DB.Model(new(models.MAdminUser)).First(&user, userId).Error
		if err != nil {
			c.Abort()
			c.JSON(http.StatusOK, gin.H{
				"success": false,
				"code":    33000,
				"msg":     "Token错误",
			})
			return
		}
		if user.Token != token {
			c.Abort()
			c.JSON(http.StatusOK, gin.H{
				"success": false,
				"code":    33000,
				"msg":     "Token error",
			})
			return
		}
		c.Next()
	}
}

// 验证请求头
func AuthToken() gin.HandlerFunc {
	return func(c *gin.Context) {
		//从请求头获取数据
		token := c.GetHeader("token")
		userId, err := strconv.Atoi(c.GetHeader("userId")) //将字符串转为int
		//调用解析token方法
		UserClaim, err := define.AnalyseToken(token)
		if err != nil {
			c.Abort() //终止函数
			c.JSON(http.StatusOK, gin.H{
				"success": false,
				"code":    33000,
				"msg":     "超过登录时间！",
			})
			return
		}
		if UserClaim.UserId != userId {
			c.Abort()
			c.JSON(http.StatusOK, gin.H{
				"success": false,
				"code":    33000,
				"msg":     "超过登录时间！",
			})
			return
		}
		//数据库获取
		var user models.MMember
		//根据主键查询
		err = models.DB.Model(new(models.MMember)).First(&user, userId).Error
		if err != nil {
			c.Abort()
			c.JSON(http.StatusOK, gin.H{
				"success": false,
				"code":    33000,
				"msg":     "超过登录时间！",
			})
			return
		}
		if user.Token != token {
			c.Abort()
			c.JSON(http.StatusOK, gin.H{
				"success": false,
				"code":    33000,
				"msg":     "超过登录时间！",
			})
			return
		}
		c.Next()
	}
}
